/**
 * 角色管理
 */
var Role = function() {

	var me = this;

	return {

		init : function() {
		},

		search : function() {
			$('#data-grid').datagrid({
				url : '/admin/role/search',
				queryParams : App.dataGridQueryParams('search-form')
			});
		},

		beforeAdd : function() {
			$('#add-dialog').dialog('open');
		},

		addRole : function() {
			$('#add-form').form('submit', {
				url : '/admin/role/save',
				onSubmit : function() {
					return $(this).form('validate');
				},
				success : function(result) {
					result = $.parseJSON(result);
					if (result.success == true) {
						$('#add-dialog').dialog('close');
						$('#data-grid').datagrid('reload');
					}
					$.messager.show({
						title : '信息',
						msg : result.data
					});
				}
			});
		},

		/** 修改准备 */
		beforeUpdate : function() {
			var row = $('#data-grid').datagrid('getSelected');
			if (row) {
				$('#add-dialog').dialog('open').dialog('setTitle', '编辑');
				$('#add-form').form('load',
						'/admin/role/queryById?id=' + row.id);
				$('#role').textbox('readonly');
			} else {
				$.messager.alert('Warning', '请选择要修改的数据');
			}
		},

		/** 删除 */
		deleteRole : function() {
			var row = $('#data-grid').datagrid('getSelected');
			if (row) {
				$.messager.confirm('Confirm', '确定要删除此信息吗？', function(ok) {
					if (ok) {
						$.post('/admin/role/delete', {
							role : row.id
						}, function(result) {
							$.messager.show({
								title : '信息',
								msg : result.data
							});
							$('#data-grid').datagrid('reload');
						}, 'json');
					}
				});
			} else {
				$.messager.alert('Warning', '请选择要删除的信息');
			}
		},

		beforeAuthorization : function() {
			var row = $('#data-grid').datagrid('getSelected');
			if (row) {
				$('#authorization-tree').tree({
					url : '/admin/permission/queryByRole?roleId=' + row.id,
					onLoadSuccess : function(node, data) {
						$('#add-authorization').dialog('open');
						$('#add-authorization').dialog('move', {
							top: 80
						});
					}
				});
				$('#roleId').val(row.id);
			} else {
				$.messager.alert('Warning', '请选择要修改的数据');
			}
		},
		
		/**授权*/
		authorization : function() {
			var nodes = $('#authorization-tree').tree('getChecked');
			var permissions = [];
			for (var i = 0; i < nodes.length; i++) {
				permissions.push(nodes[i].id);
			}
			nodes = $('#authorization-tree').tree('getChecked', 'indeterminate');
			for (var i = 0; i < nodes.length; i++) {
				permissions.push(nodes[i].id);
			}
			var params = {permissions: permissions.join(','), roleId: $('#roleId').val()};
			$.post('/admin/role/authorization', params, function(result) {
				if (result.success == true) {
					$('#add-authorization').dialog('close');
				}
				$.messager.show({
					title : '信息',
					msg : result.data
				});
			});
		},

		closeAuthorizationDialog : function() {
			$('#add-authorization').dialog('close');
		}
	}

}();